package com.ruoyi.cms.fileinfo.service.impl;

import com.ruoyi.cms.fileinfo.domain.SysFileInfo;
import com.ruoyi.cms.fileinfo.mapper.SysFileInfoMapper;
import com.ruoyi.cms.fileinfo.service.ISysFileInfoService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文件管理Service业务层处理
 *
 * @author toumakazusa
 * @since 1.0.0
 */
@Service
public class SysFileInfoServiceImpl implements ISysFileInfoService {


    @Autowired
    private SysFileInfoMapper sysFileInfoMapper;


    @Override
    public int deleteSysFileInfoByFileObjectName(String fileObjectName) {
        SysFileInfo sysFileInfo = sysFileInfoMapper.selectSysFileInfoByFileObjectName(fileObjectName);
        if (sysFileInfo != null) {
            String filePath = RuoYiConfig.getProfile() + StringUtils.substringAfter(sysFileInfo.getFilePath(), Constants.RESOURCE_PREFIX);
            FileUtils.deleteFile(filePath);
            return sysFileInfoMapper.deleteSysFileInfoByFileObjectName(fileObjectName);
        }
        return -1;
    }

    @Override
    public int deleteSysFileInfoByFileId(Long fileId) {
        SysFileInfo sysFileInfo = sysFileInfoMapper.selectSysFileInfoByFileId(fileId);
        if (sysFileInfo != null) {
            String filePath = RuoYiConfig.getProfile() + StringUtils.substringAfter(sysFileInfo.getFilePath(), Constants.RESOURCE_PREFIX);
            FileUtils.deleteFile(filePath);
        }
        return sysFileInfoMapper.deleteSysFileInfoByFileId(fileId);
    }

    @Override
    public SysFileInfo selectSysFileInfoByFileId(Long fileId) {
        return sysFileInfoMapper.selectSysFileInfoByFileId(fileId);
    }

    @Override
    public List<SysFileInfo> selectSysFileInfoList(SysFileInfo sysFileInfo) {
        return sysFileInfoMapper.selectSysFileInfoList(sysFileInfo);
    }


    @Override
    public int insertSysFileInfo(SysFileInfo sysFileInfo) {
        sysFileInfo.setCreateTime(DateUtils.getNowDate());
        return sysFileInfoMapper.insertSysFileInfo(sysFileInfo);
    }

    @Override
    public int deleteSysFileInfoByFileIds(Long[] fileIds) {
        for (int i = 0; i < fileIds.length; i++) {
            Long fileId = fileIds[i];
            SysFileInfo sysFileInfo = sysFileInfoMapper.selectSysFileInfoByFileId(fileId);
            String filePath = RuoYiConfig.getProfile() + StringUtils.substringAfter(sysFileInfo.getFilePath(), Constants.RESOURCE_PREFIX);
            FileUtils.deleteFile(filePath);
        }
        return sysFileInfoMapper.deleteSysFileInfoByFileIds(fileIds);
    }
}
